package job

import (
	json2 "encoding/json"
	"fmt"
	"log"
	"os"
	"strconv"
	"time"
	"xiaoniu-job/internal/cache"
	"xiaoniu-job/internal/config"
	"xiaoniu-job/pkg"
	"xiaoniu-job/pkg/util"
)

// CommonLogic 任务公共逻辑
func CommonLogic(handleFunc func(taskLog *log.Logger, request *pkg.ClientTaskRequest) string,
	realParam *pkg.ClientTaskRequest) {
	res := ""
	file := config.ClientRation.LogPath + "/task/" + strconv.FormatUint(realParam.TaskId, 10) + ".log"
	logFile, err := os.OpenFile(file, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0766)

	defer logFile.Close()
	if err != nil {
		res = "执行任务时生成日志文件出错, "
	}
	localLogger := log.New(logFile, "["+realParam.TaskLabel+"]", log.LstdFlags|log.Lshortfile|log.Ldate|log.Ltime)

	localLogger.Println("in_param is", realParam.TaskParam)

	// 执行具体的业务逻辑
	res = handleFunc(localLogger, realParam)

	var taskResult = pkg.ClientTaskResult{
		Result:     res,
		FinishTime: fmt.Sprintf("\"%s\"", time.Now().Format("2006-01-02 15:04:05")),
	}

	url := realParam.LogCallBackUrl
	if config.ClientRation.AdminServer != "" {
		url = config.ClientRation.AdminServer + "/api/client/callBack"
	}
	bodyMap := make(map[string]interface{})
	bodyMap["taskId"] = realParam.TaskId
	bodyMap["taskResult"] = taskResult
	// 尝试向服务端发送最终结果
	try, _ := strconv.Atoi(config.ClientRation.TryCount)
	for i := 0; i < try; i++ {
		json, e := util.PostJson(url, bodyMap)
		marshal, _ := json2.Marshal(json)
		localLogger.Println("发送回调日志：", string(marshal))
		if e != nil {
			continue
		}
		// 如果发送请求成功，直接return
		if json.Code == 0 {
			return
		}
	}
	// 将数据保存到内存中，提供给服务端后续读取
	cache.CACHE[realParam.TaskId] = taskResult
}

var LocalTaskMap = make(map[string]interface{}, 0)

// RegisterTask 注册任务
func RegisterTask(taskId string, handler func(task *log.Logger, request *pkg.ClientTaskRequest) string) {
	LocalTaskMap[taskId] = handler
}
